<template>
  <c-popup v-model="modelValue">
    <view class="sku-wrap">
      <c-icon class="close" size="40" color="var(--color-gray)" @tap="modelValue = false" icon="close-circle-filled" />
      <view class="sku-hd">
        <c-img class="img" preview :src="smallImg" mode="aspectFill" />
        <view>
          <c-number class="sku-price" :value="selectSku?.salePrice ?? attrs.minPrice" prefix="￥" />
          <view class="sku-select" :class="{ ac: selectSome.length > 0 }">
            {{ selectSome.length < 0 ? '请选择' : '已选' }}
            <text>{{ selectText }}</text>
          </view>
        </view>
      </view>
      <template v-if="props.specProps && props.specProps.length">
        <view class="sku-rows" v-for="prop in props.specProps" :key="prop.propId">
          <view class="sku-title">{{ prop.name }}</view>
          <view class="sku-select">
            <template v-if="prop.images && Object.keys(prop.images).length">
              <view v-for="(item, i) in prop.values" :key="i" class="img-option" @tap="onSelect(prop, item)" :class="{ active: select[prop.propId] == item }">
                <c-img class="img" mode="aspectFill" :src="prop.images[item]" />
                <view class="option">{{ item }}</view>
              </view>
            </template>
            <template v-else>
              <view class="option" v-for="(item, i) in prop.values" :key="i" @tap="onSelect(prop, item)" :class="{ active: select[prop.propId] == item }">{{ item }}</view>
            </template>
          </view>
        </view>
      </template>
      <template v-else-if="attrs.goodsType == 0">
        <view class="sku-rows">
          <view class="sku-title">规格</view>
          <view class="sku-select">
            <view class="option active">默认规格</view>
          </view>
        </view>
      </template>
      <view class="flex-between al-center">
        <view class="sku-title">
          库存
          <text class="font-mini color-gray" v-if="stock > 500">库存充足</text>
          <text class="font-mini color-gray" v-else-if="stock > 100">100+</text>
          <text class="font-mini color-gray" v-else-if="stock > 10">{{ stock }}</text>
          <text class="font-mini color-gray" v-else-if="stock > 0">仅剩{{ stock }}</text>
          <text class="font-mini color-gray" v-else>已售罄</text>
        </view>
        <view><c-counter v-model="qty" v-if="showQty" :min="1" :max="attrs.isDeductStock ? selectSku?.stock : 999" /></view>
      </view>
      <view class="join">
        <c-button type="danger" @tap="onTap" :disabled="stock == 0">{{ stock == 0 ? '已售罄' : props.btnText }}</c-button>
      </view>
    </view>
  </c-popup>
</template>
<script setup>
import { CButton, CImg, CPopup, CNumber, CIcon, CCounter } from '@/components';
import toast from '@/utils/toast';
import { View, Text } from '@tarojs/components';

import { computed, ref, useAttrs, watch } from 'vue';

const modelValue = defineModel(Boolean);
const props = defineProps({
  isOnSale: Boolean,
  specProps: Array,
  bannerImgs: Array,
  onConfirm: Function,
  btnText: {
    type: String,
    default: '加入购物车'
  },
  skuList: Array
});

const attrs = useAttrs();
const select = ref({});
const qty = ref(1);
const selectSome = computed(() => Object.values(select.value).filter(a => a != null));
const selectText = computed(() => {
  if (selectSome.value.length > 0) {
    const names = props.specProps.filter(prop => select.value[prop.propId] && prop.values.includes(select.value[prop.propId])).map(prop => select.value[prop.propId]);
    return names.join('、');
  }
  return (props.specProps ?? []).map(a => a.name).join('、');
});

const clear = () => {
  select.value = {};
  qty.value = 1;
};

const selectSkuIndex = computed(() => {
  if (!props.skuList) {
    return -1;
  }
  return props.skuList.findIndex(sku => {
    if (!sku.skuProps) return false;
    return sku.skuProps.every(prop => select.value[prop.propId] == prop.value);
  });
});

const smallImg = computed(() => {
  const goodsImg = (props.bannerImgs ?? [])[0];
  const index = selectSkuIndex.value;
  if (index < 0) {
    return goodsImg;
  }
  return props.skuList[index].smallImg || goodsImg;
});

const selectSku = computed(() => {
  if (!props.skuList) {
    return null;
  }
  return props.skuList[selectSkuIndex.value];
});

const stock = computed(() => {
  if (!attrs.isDeductStock) {
    return 999;
  }
  if (selectSkuIndex.value < 0) {
    return props.skuList.sum(a => a.stock);
  }
  return selectSku.value.stock;
});

const onSelect = (prop, value) => {
  if (select.value[prop.propId] == value) {
    select.value[prop.propId] = '';
  } else {
    select.value[prop.propId] = value;
  }
};
const showQty = computed(() => {
  if (!props.specProps || (props.specProps.length == 0 && props.skuList.length == 1)) {
    return true;
  }
  if (selectSkuIndex.value >= 0) {
    return true;
  }
  return false;
});

const onTap = async () => {
  let sku = null;
  if (!props.specProps || (props.specProps.length == 0 && props.skuList.length == 1)) {
    sku = props.skuList[0];
  } else {
    if (selectSkuIndex.value < 0) {
      toast.error('请选择规格');
      return;
    }
    sku = selectSku.value;
  }
  if (props.onConfirm) {
    await props.onConfirm({
      sku: sku,
      qty: qty.value
    });
    modelValue.value = false;
    clear();
  }
};
</script>
<style lang="scss">
.sku-wrap {
  border-radius: 20px 20px 0 0;
  padding: 30px;
  padding-bottom: var(--safe-bottom);
  .sku-hd {
    display: flex;
    .img {
      width: 140px;
      height: 140px;
      margin-right: 20px;
      border-radius: 5px;
      overflow: hidden;
      background-color: var(--color-background);
    }
    .sku-price {
      font-weight: bold;
      font-size: 48px;
      margin: 10px 0;
      display: block;
      color: var(--color-danger);
    }
    .sku-select {
      font-size: 26px;
      color: var(--color-gray);
      &.sku-select {
        color: var(--color-default);
      }
    }
  }
  .sku-title {
    margin: 30px 0;
    font-weight: 500;
    color: var(--color-default);
  }
  .sku-rows {
    margin-right: -10px;
    padding-bottom: 20px;

    .sku-select {
      display: flex;
      .option {
        padding: 0 24px;
        font-size: 28px;
        box-sizing: content-box;
        line-height: 60px;
        text-align: center;
        border-radius: 10px;
        background-color: #f7f8f9;
        margin-right: 10px;
        border: var(--onepx) solid var(--color-line);
        transition: all 0.3s;
        &.active {
          border-color: var(--color-danger);
          background: rgba(254, 48, 25, 0.05);
          color: var(--color-danger);
        }
      }
      .img-option {
        width: 120px;
        box-sizing: content-box;
        border-radius: 10px;
        overflow: hidden;
        margin-right: 10px;
        border: var(--onepx) solid var(--color-line);
        transition: all 0.3s;
        .img {
          height: 110px;
          width: 100%;
        }
        .option {
          width: 100%;
          box-sizing: border-box;
          margin-right: 0px;
        }
        &.active {
          border-color: var(--color-danger);
          color: var(--color-danger);
          .option {
            background: rgba(254, 48, 25, 0.05);
          }
        }
      }
    }
  }

  .join {
    margin-top: 30px;
  }
  .close {
    position: absolute;
    right: 30px;
    top: 30px;
  }
}
</style>
